/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-06 13:59:36
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-07 10:11:45
 * @Description: file content
 */

import { Agent, IBoot } from "egg";

import startWebSocketServer from "./lib/agent";
import { IPCData } from "./ws";

export default class AppInitBoot implements IBoot {
  private readonly agent: Agent;

  constructor(agent: Agent) {
    this.agent = agent;
    // agent进程调用 启动ws server
    const wss = startWebSocketServer(agent);
    // agent上挂载webSocketServer调用入口。
    agent.wss = wss;
    // example 拿到wss实例作为agent上处理业务逻辑的入口。
    if (agent.wss) {
      // 接收前端消息事件。
      agent.wss.work.on("abc", (data: IPCData) => {
        console.log(process.pid);
        console.log(data);
        data.data = { is: "agent" };
        // 发送消息给前端。
        agent.wss?.work.emit("ws-response", data);
      });
    }
  }

  async willReady() {
    // const port = this.agent.config.cluster.listen.port;
    console.log(this.agent.config.cluster.listen.port);

    // this.ws();

    //local本地开发环境执行一次sync，将模型入数据库。
    if (this.agent.config.env !== "prod") {
      // await this.app.model.sync({ force: true });
      // await this.app.model.sync({ alter: true });
    }
  }
}
